
/***
 * sample：<INPUT class=common-button actionType="ajaxSubmit" script="|replace(app-content);|$('#emailMessage').html('mapJson['email']');$('#emailMessage').html('mapJson['password']');" style="width:50px" type=button value="confirm">
 */
var component = new Object;
component.FrameAjax = function() {
    this.iframe = null;
    this.listener = null;
    this.arr = null;
}

component.FrameAjax.prototype = {
    load:function(href, arr, listener) {
		var self = this;
		this.iframe = document.createElement("iframe");
		$(this.iframe).css("display", "none");
	    $(document.body).append(this.iframe);  
        this.listener = listener;
        //alert(this.listener);
        this.iframe.src = href;        
        this.arr = arr;
        
        $(this.iframe).bind("load", function() {
        	//alert(self.listener + " " + self.iframe);
            self.listener.call(null, self.iframe.contentWindow.document.body.innerHTML);
            $(self.iframe).remove();
        });
    }

}



$(document).ready(function() {	
	init(document);	
	//window.setTimeOut("init(id)", 200);
});
 
function dealPngImg(id) {
    $(id).find("img").each(function() {        
        var img = this;
        //alert("begin:" + img.src);
        var imgName = img.src.toUpperCase()
        if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
        {
            //alert(img.src);
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText
            if (img.align == "left") imgStyle = "float:left;" + imgStyle;
            if (img.align == "right") imgStyle = "float:right;" + imgStyle;
            //if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;  
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
                + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
                + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
                //img.outerHTML = strNewHTML;     
                $(img).replaceWith(strNewHTML);
             //   alert(strNewHTML);
        }
    });
}

function adjustElementId(el, identify) {
	var id = $(el).attr("id");
	if(id == null || $.trim(id) == "") {
		$(el).attr("id", new Date().getTime() + "_" + identify);
	}			
}

function getBrowse() {
	 var Sys = {};
     var ua = navigator.userAgent.toLowerCase();
     var s;
     (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
     (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
     (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
     (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
     (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
     return Sys;
}

var identify = 0;
function loadComponent(e) {
//	alert(e);
	var self = e;
	var script = $(e).attr("script");
	identify++;
	//alert(script);
	if(script == null || script == "") { 
		adjustElementId(e, identify);			
		script = $(e).attr("id");
		//$("#out").html($("#out").html() + "id:" + script + " identify:" + identify + "<br>");
	}
	var arr = parseScript(script);	
	//alert(arr.beforeAction);
	if(arr.beforeAction != "") {			   
	    var s = parseFunction(arr.beforeAction, self, identify);     
	    
	    var result = executeFunctions(s, document);  
	    //alert(result);
			if(result != null && result!="undefined" && !result ) {
				return false;
			}
		}
		var href=$(self).attr("href");
		if(isIE()) {
			href = encodeURI(href);
		}
	var params={
		url: href,
		data:""
	}
	if(href.indexOf("?")>0){
		params.url=href.substring(0, href.indexOf("?"));//包含?
		params.data=href.substring(href.indexOf("?")+1);
		if(params.data.indexOf("&") == 0) {
			params.data=params.data.substring(1);
		}
	}
	new component.FrameAjax().load(href, arr, function(data) {  
//		alert(data);
		loadAndRunAction(arr, self, data, identify);
    });
}

function ajaxLink(el) {
	var $this=$(el);
	el.onclick=function() {
		identify++;
		var tmp = this;
		var arr = parseScript($this.attr("script"));	
		if(arr.beforeAction != "") {
			var s = parseFunction(arr.beforeAction, tmp, identify);     
		    var result = executeFunctions(s, document);  
   			if(result != null && result!=undefined && !result ) {
   				return false;
   			}
		}
		var href=$this.attr("href");
		if(isIE()) {href = encodeURI(href);}
		var params={url: href,data:""}
		var hrefLength=href.indexOf("?");
		if(hrefLength>0){//包含?
			params.url=href.substring(0, hrefLength);
			params.data=href.substring(hrefLength+1);
			if(params.data.indexOf("&") == 0) {
				params.data=params.data.substring(1);
			}
		}
		$.ajax({
			type: "POST",  
			url: params.url,
			data:params.data,
			cache:false,
			contentType:"application/x-www-form-urlencoded;charset=UTF-8",
			success : function(data) {	
				loadAndRunAction(arr, tmp, data, identify);
			}});
		return false;
	};
	
}

function ajaxSubmit(el) {
	$(el).click(function() {
		identify++;	
		var $this=$(this);
		var arr = parseScript($this.attr("script"));	
		var tmp = this;
		if(arr.beforeAction != "") {			   
		    var s = parseFunction(arr.beforeAction, tmp, identify);     
		    var result = executeFunctions(s, document);  
   			if(result != null && result!="undefined" && !result ) {
   				return false;
   			}
		}
		
		var $formElement = $this.parents("form:first");
		$formElement.ajaxSubmit(function(data, status) {	
			
			loadAndRunAction(arr, this, data, identify);	
		});
		return false;
	});
}

function init(el) {

	var numload = 0;
	$el=$(el);
	var i = 0;
	$el.find("*[actionType]").each(function() {
		i++;
		var actionType = $(this).attr("actionType");
		if(actionType == "loadedComponent") {
			var e = this;
			numload++;
			window.setTimeout(function() {
				return loadComponent(e);
			}, numload * 300);
		}
		else if(actionType == "ajaxLink") {
			ajaxLink(this);
		}
		else if(actionType == "ajaxSubmit") {
			ajaxSubmit(this);
		}
	});
}

function parseScript(script) {
	var result = {
		beforeAction:"",
		success:"",	
		fail:""	
	};
	var s = script.split("|");
	if(s.length == 1) {
		result.success = s[0];
	}
	else if(s.length == 2) {
		result.beforeAction = s[0];
		result.success = s[1];
	}
	else if(s.length == 3) {
		result.beforeAction = s[0];
		result.success = s[1];
		result.fail = s[2];
	}
	return result;
}

function parseJsonMessage(msessgeval) {
	msessgeval = $.trim(msessgeval);
	var message = msessgeval.replace(/\n/g, "\\n");	 
	if(message==""){
		return null;
	}
	return eval("(" + message + ")");
}

function parseFunctionJsonParam(jsonId, f, json) {
	var r = new RegExp(jsonId + "\\[\\'([A-Za-z0-9]+)\\'\\]", "i");
	while(f.search(r) != -1) {
		f = f.replace(r, json[RegExp.$1]);
	}
	return f;
}

function loadAndRunAction(arr, e, data, identify) {	
	//alert(data);
	var element = document.createElement("div");	
	$(element).html(data);
	var jsonEls = $(element).find("*[type=json]");
	var json = null;
	var result = "true";
	if(jsonEls.length > 0) {
		jsonEls.each(function() {			
			json = parseJsonMessage($(this).html());
			if(json != null && json["result"] != "undefined") {
				result = json["result"];
			}
			//result = json != null ? json["result"] : "false";
			if(arr.success != null && arr.success != "")
				arr.success = parseFunctionJsonParam($(this).attr("id"), arr.success, json);
			if(arr.fail != null && arr.fail != "")
				arr.fail = parseFunctionJsonParam($(this).attr("id"), arr.fail, json);
		});
	}
	
	if(isTrue(result)) {
		var s = parseFunction(arr.success, e, identify);    
    	executeFunctions(s, element);
    }
    else {
    	var fail = parseFunction(arr.fail, e, identify);    
    	executeFunctions(fail, element);
    }
    
}

function executeFunctions(script, data) {
	var fs = script.split(";");
	var result = true;
	for(var i = 0; i < fs.length; i++) {
		fs[i] = $.trim(fs[i]);
		if(fs[i] == "") {
			continue;
		}
		//alert(fs[i]);
		if(fs[i].indexOf("replace(") == 0) {
			var param = fs[i].substring("replace(".length, fs[i].length - 1);
			//alert("replace:" + fs[i]);
			replace(param, data);
		}else if(fs[i].indexOf("replaceTabSelected(") == 0) {
			var param = fs[i].substring("replaceTabSelected(".length, fs[i].length - 1);
			replaceTabSelected(param, data);
		}else if(fs[i].indexOf("replaceSelectEvent(") == 0) {
			var param = fs[i].substring("replaceSelectEvent(".length, fs[i].length - 1);
			replaceSelectEvent(param, data);
		}
		else {
			//alert(1);
			result = eval(fs[i]);
			//alert("eval:" + fs[i] + " " + result);
		}
		//判断只要有一个fasle就返回
		if(result != null && result!=undefined && !result ) {
				//alert("false");
				return false;
		}
	}
	//alert("result:" + result);
	return result;
	
}


function replace(param, data) {
	param = param.replace(/['"]([^'"]*)['"]/g, "$1");
	var s = param.split(",");
	var targetData=data;
	if(s.length == 2) {
		//alert(s[1]);
		targetData = $(data).find("#" + s[1])[0];
	}
	var html=$(targetData).html();
	var source = document.getElementById(s[0]);
	if(null == source){
		source = $("<div></div>").attr("id",s[0]).css("display","none").get(0);
		$(source).appendTo("body");
	}
	$(source).find("*[actionType]").each(function() {
		this.onclick = null;
	});
	//alert("replace:" + s[0]);
	if(html&&html!=""){$(source).html(html);}
	init("#" + s[0]);
}

function replaceTabSelected(tabName,data) {
	var tabs = $('#'+ tabName);
	var selected = tabs.tabs('option', 'selected');
	var replaceDivs = $(tabs.children("div"));
	var replaceDiv = $(replaceDivs[selected]);
	replaceDiv.html($(data).html());
	init(replaceDiv);
}

function replaceSelectEvent(subMenuId,data) {
	var curli = $('#'+subMenuId).find("li[class=currentSelected]")[0];
	var replaceDiv = $('#' + curli.attr('id') + 'eventContent');
	replaceDiv.html($(data).html());
	init(replaceDiv);
}

function parseFunction(f, el, identify) {
	adjustElementId(el, identify);
	
	var re = /this/g;
	f = f.replace(re, "$('#" + $(el).attr("id") + "').get(0)");	
	//alert(f);
	
	return f;
}

function isTrue(s) {
	return $.trim(s) == "true";
}
function retrunLogin(win,url) {
	//alert('操作超时,请重新登陆');
	var v = win;
	while(v!=v.parent) {
		v = v.parent;
	}
	v.location.href=url;
}

